//
//  ViewController.swift
//  RxMoya
//
//  Created by XuHao on 2018/4/26.
//  Copyright © 2018年 XuHao. All rights reserved.
//

import UIKit
import Moya
import RxSwift
import ObjectMapper
import RxCocoa
import MJRefresh

class ViewController: UIViewController {

    var bag : DisposeBag = DisposeBag()
    
    var tableView: UITableView!
    
    let viewModel = MZTViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        bindView()

    }
    
    
    func setupUI()  {
        
        var tableH = UIScreen.main.bounds.height - 64
        var tableY:CGFloat = 64
        if UIScreen.main.bounds.height == 812 {
            
            tableH = UIScreen.main.bounds.height - 88
            tableY = 88
        }
      
        tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: tableY, width: UIScreen.main.bounds.width, height:tableH ), style: UITableViewStyle.plain)
        view.addSubview(tableView)

        tableView.register(UINib.init(nibName: "MZTCell", bundle: nil), forCellReuseIdentifier: cellID)

        tableView.rowHeight = 467

        tableView.tableFooterView = UIView.init()
        
        
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentBehavior(rawValue: 2)!
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        };
        

        viewModel.tableView = tableView

        viewModel.binding()
        
        weak var weakself = self
        
        tableView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            
            weakself?.viewModel.requestConmond.onNext(true)
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingBlock: {
            weakself?.viewModel.requestConmond.onNext(false)
        })
        
        tableView.mj_header.beginRefreshing()
        
    }
    
    func bindView()  {
        
        tableView.rx
            .itemSelected
            .subscribe(onNext: {
                (index : IndexPath) in
                print("\(index.row)")
            })
            .disposed(by: bag)
        
        tableView.rx
            .modelSelected(MZTModel.self)
            .subscribe(
                onNext:{
                    value in
                    
                    print(value.title!)
            })
            .disposed(by: bag)
    }

 
}

